#!/usr/bin/perl -w

### Notes:
# The -T for security check would help to protect the script but was giving error and was removed.
# The arguments been used as parameterson external commands/scripts. For the input file name, all "'` and ; are stripped and for the output formats, only alphanumeric _ and & are allowed.  Feel free ADD extra protectiong.
# TODO: Handle undefined $1
# TODO: Lock files
# TODO: Change time out for BM and perhaps Compressor


use XML::XPath;
use POSIX 'strftime';
#use URI::Escape;

use FCTranscode;


### Start og main program ###

# Using to calculate duration which is used to select the dvd quality 
$hours = 0;
$mins = 0;
$secs = 0;

# TODO - Process command line argument arguments 
#if ($#ARGV!=1) {
#	# Usage: $0 input_file out_formats=f1[&out_formats=f2[&out_f...]]
#	error_die("ERROR:3001: Wrong number of parameters for $0.");
#	exit 0;
#}

# Filtering arguments and building format list (if changing the pattern please do the same on the calling program(ServiceInterface.java))
# Need to create a filter for ARGV[0]
$ARGV[0] =~ s/[;"'\`\\\|]//g; # Hope that filtering \ won't make problems like.. dir\ name... TODO: add & and maybe others
$input_name = $ARGV[0];

# Get media duration (maybe put a few checks/warnings?)
unless (-e $mediainfo) {
	error_die("ERROR:3002: mediainfo not found.");
}
$raw_minfo = `$mediainfo --Output=XML \'$input_name\'`;
$xml_content = XML::XPath->new($raw_minfo)	or error_die("ERROR:3003: Could not instantiate XPath.");
# Not sure if the bellow should be an error or warning. Need to match the quickwarn and ERROR:
$duration_raw = $xml_content->getNodeText('/Mediainfo/File/Video/Duration') or quick_warn("ERROR:3004: Invalid node path for mediainfo XML.");

# Looks like then warnings comes from $1 been undefined. TODO - Check $1 before assignment 
$duration_raw =~ /(\d+)h/;
$hours = $1;
$duration_raw =~ /(\d+)mn/;
$mins = $1;
$duration_raw =~ /(\d+)s/;
$secs = $1;

$totalsecs = ((($hours*60)+$mins)*60)+$secs+1;

print "DURATION:$totalsecs\n";
	
       
